$(function () {
    validateData();
    $("body").on('click','#selectCourse',function () {//选择课程
        selectCourse({
            selectType:'checkbox',
            type:1,
            callback:'selectCourseCallback'
        });
    }).on('click','#course-btn',function () {//推广设置-选择课程
        selectCourse({
            selectType:'checkbox',
            type:1,
            callback:'courseCallback'
        });
    }).on('click','#selectExam',function () {//选择试卷
        selectExam({
            'selectType':'checkbox',
            'sale':1,
            'callback':'selectExamCallback'
        });
    }).on('click','#exam-btn',function () {//推广设置-选择试卷
        selectExam({
            'selectType':'checkbox',
            'sale':1,
            'callback':'examCallback'
        });
    }).on('click','#selectBook',function () {//选择图书
        selectBook({
            selectType:'checkbox',
            callback:'selectBookCallback'
        });
    }).on('click','#book-btn',function () {//推广设置-选择图书
        selectBook({
            selectType:'checkbox',
            callback:'bookCallback'
        });
    }).on('click','#selectMember',function () {//选择会员
        selectMember({
            'selectType':'checkbox',
            'callback':'selectMemberCallback'
        });
    }).on('click','#member-btn',function () {//推广设置-选择会员
        selectMember({
            'selectType':'checkbox',
            'callback':'memberCallback'
        });
    }).on('click','.delete-shop',function () {//推广设置-删除商品
        $(this).parent().remove();
    });

    //初始化课程免费直播
    selectOpenCourse();

    initLayerDate("#startDate",true);
    initLayerDate("#endDate",true);
    //初始化保存优惠券
    saveCoupon();

    inputRadioSel($("input[type='radio']"), selectCall);//查询所有单选按钮，回调方法selectCall

    $('body').on('click', '.deleteCourse', function () {//删除课程
        var dataId = $(this).parents('tr').data('id');
        var obj = $(this).parents('tr');
        deleteSelectCourse(dataId, obj)
    }).on('click', '.deleteExam', function () {//删除试卷
        var dataId = $(this).parents('tr').data('id');
        var obj = $(this).parents('tr');
        deleteExam(dataId, obj);
    }).on('click', '.deleteBook', function () {//删除图书
        var dataId = $(this).parents('tr').data('id');
        var obj = $(this).parents('tr');
        deleteBook(dataId, obj);
    }).on('click', '.deleteMember', function () {//删除图书
        var dataId = $(this).parents('tr').data('id');
        var obj = $(this).parents('tr');
        deleteMember(dataId, obj);
    }).on('click', '.deleteOpenCourse', function () {//删除免费直播
        var em = $(this).parents('tr');
        var dataId = em.data('id');
        deleteSelectOpenCourse(dataId, em)
    }).on('click', '#onBack', function () {//取消
        window.history.go(-1);
    });
});

//==========================================================
/**
 * 推广设置 -选择课程回调
 * @param result
 */
function courseCallback(result) {
    var oldList = $("#course-box").find('div');
    var courseIds = '';
    if(oldList.length > 0){
        courseIds =','+ (oldList.map(function () {
            return $(this).data('id');
        }).get().join(",")) +',';
    }
    var context ='';
    $.each(result,function (index,course) {
        if(courseIds.indexOf(','+course.id+',') == -1){
            context += '<div class="row well well-sm m-b-none" data-id="'+course.id+'" data-type="COURSE">';
            context += '<section class="col-sm-10">';
            context += '<ol class="breadcrumb">';
            context += '<li class="active" >'+course.courseName+'</li>';
            context += '</ol></section>';
            context += '<section class="col-sm-2 text-center delete-shop">';
            context += '<a href="javascript:void(0);" class="c-master fs14" title="删除"><i class="fa fa-close"></i></a>';
            context += '</section></div>';
        }
    });
    $("#course-box").append(context);
}

/**
 * 推广设置 -选择试卷回调
 * @param result
 */
function examCallback(result) {
    var oldList = $("#exam-box").find('div');
    var examIds = '';
    if(oldList.length > 0){
        examIds =','+ oldList.map(function () {
            return $(this).data('id');
        }).get().join(",") +',';
    }
    var context ='';
    $.each(result,function (index,exam) {
        if(examIds.indexOf(','+exam.id+',') == -1){
            context += '<div class="row well well-sm m-b-none" data-id="'+exam.id+'" data-type="EXAM">';
            context += '<section class="col-sm-10">';
            context += '<ol class="breadcrumb">';
            context += '<li class="active" >'+exam.examName+'</li>';
            context += '</ol></section>';
            context += '<section class="col-sm-2 text-center delete-shop">';
            context += '<a href="javascript:void(0);" class="c-master fs14" title="删除"><i class="fa fa-close"></i></a>';
            context += '</section></div>';
        }
    });
    $("#exam-box").append(context);
}
/**
 * 推广设置 -选择图书回调
 * @param result
 */
function bookCallback(result) {
    var oldList = $("#book-box").find('div');
    var bookIds = '';
    if(oldList.length > 0){
        bookIds =','+ oldList.map(function () {
            return $(this).data('id');
        }).get().join(",") +',';
    }
    var context ='';
    $.each(result,function (index,book) {
        if(bookIds.indexOf(','+book.id+',') == -1){
            context += '<div class="row well well-sm m-b-none" data-id="'+book.id+'" data-type="BOOK">';
            context += '<section class="col-sm-10">';
            context += '<ol class="breadcrumb">';
            context += '<li class="active" >'+book.bookName+'</li>';
            context += '</ol></section>';
            context += '<section class="col-sm-2 text-center delete-shop">';
            context += '<a href="javascript:void(0);" class="c-master fs14" title="删除"><i class="fa fa-close"></i></a>';
            context += '</section></div>';
        }
    });
    $("#book-box").append(context);
}
/**
 * 推广设置 -选择会员回调
 * @param result
 */
function memberCallback(result) {
    var oldList = $("#member-box").find('div');
    var bookIds = '';
    if(oldList.length > 0){
        bookIds =','+ oldList.map(function () {
            return $(this).data('id');
        }).get().join(",") +',';
    }
    var context ='';
    $.each(result,function (index,member) {
        if(bookIds.indexOf(','+member.id+',') == -1){
            context += '<div class="row well well-sm m-b-none" data-id="'+member.id+'" data-type="MEMBER">';
            context += '<section class="col-sm-10">';
            context += '<ol class="breadcrumb">';
            context += '<li class="active" >'+member.memberName+'</li>';
            context += '</ol></section>';
            context += '<section class="col-sm-2 text-center delete-shop">';
            context += '<a href="javascript:void(0);" class="c-master fs14" title="删除"><i class="fa fa-close"></i></a>';
            context += '</section></div>';
        }
    });
    $("#member-box").append(context);
}
//==========================================================


/**
 * 删除选择的课程
 * @param dataId
 * @param obj
 */
function deleteSelectCourse(dataId, obj) {
    var courseIds = ',';
    var courses = $("#courseIds").val();
    var courseId = courses.split(',');
    for (var i = 0; i < courseId.length; i++) {
        if (courseId[i] != null && courseId[i] != '' && courseId[i] != dataId) {
            courseIds += courseId[i] + ",";
        }
    }
    if (courseIds.length > 1) {
        $("#courseIds").val(courseIds);
        $("#course-content-table-hd").removeClass('hide');
    } else {
        $("#courseIds").val("");
        $("#course-content-table-hd").addClass('hide');
    }
    obj.remove();
}


/**
 * 选择课程回调
 * @param result 回调数据
 */
function selectCourseCallback(result) {
    if(result!=null && result.length>0){
        var courseIds = $('#courseIds').val();
        if(courseIds==null||courseIds==''){
            courseIds =',';
        }
        $.each(result,function (index,course) {
            var courseName =course.courseName;
            var coursePrice =course.orPrice;
            if(courseIds.indexOf(","+course.id+",")==-1){
                $("#course-content-table-hd").removeClass("hide");
                courseIds +=course.id+',';
                $('#course-content').append(' <tr data-id="'+course.id+'">'+
                    '<td class="text-center">'+course.id+'</td>'+
                    '<td>'+courseName+'</td>'+
                    '<td><span class="c-red">'+coursePrice+'</span></td>'+
                    '<td class="text-center"><a class="c-master deleteCourse"  href="javascript:void(0);">删除</a></td>'+
                    '</tr>');
            }
        });
        $('#courseIds').val(courseIds);
    }
    parentId = 0;
}

/**
 * 删除试卷
 * @param dataId 试卷ID
 * @param obj
 */
function deleteExam(dataId, obj) {
    var examIds = ',';
    var examList = $("#examIds").val();
    var examIdArr = examList.split(',');
    for (var i = 0; i < examIdArr.length; i++) {
        if (examIdArr[i] != null && examIdArr[i] != '' && examIdArr[i] != dataId) {
            examIds += examIdArr[i] + ",";
        }
    }
    if (examIds.length > 1) {
        $("#examIds").val(examIds);
        $("#exam-content-table-hd").removeClass('hide');
    } else {
        $("#examIds").val("");
        $("#exam-content-table-hd").addClass('hide');
    }
    obj.remove();
}

/**
 * 选择试卷回调
 * @param exam 试卷数据
 */
function selectExamCallback(result) {
    if(result!=null && result.length>0){
        var examIds = $('#examIds').val();
        if(examIds==null||examIds==''){
            examIds =',';
        }
        $.each(result,function (index,exam) {
            var examName =exam.examName;
            var examPrice=exam.examPrice;
            if(examIds.indexOf(","+exam.id+",")==-1){
                $("#exam-content-table-hd").removeClass("hide");
                examIds +=exam.id+',';
                $('#exam-content').append(' <tr data-id="'+exam.id+'">'+
                    '<td class="text-center">'+exam.id+'</td>'+
                    '<td>'+examName+'</td>'+
                    '<td><span class="c-red">'+examPrice+'</span></td>'+
                    '<td class="text-center"><a class="c-master deleteExam"  href="javascript:void(0);">删除</a></td>'+
                    '</tr>');
            }
        });
        $('#examIds').val(examIds);
    }
}

/**
 * 删除图书
 * @param dataId 图书ID
 * @param obj
 */
function deleteBook(dataId, obj) {
    var bookIds = ',';
    var bookList = $("#bookIds").val();
    var bookIdArr = bookList.split(',');
    for (var i = 0; i < bookIdArr.length; i++) {
        if (bookIdArr[i] != null && bookIdArr[i] != '' && bookIdArr[i] != dataId) {
            bookIds += bookIdArr[i] + ",";
        }
    }
    if (bookIds.length > 1) {
        $("#bookIds").val(bookIds);
        $("#book-content-table-hd").removeClass('hide');
    } else {
        $("#bookIds").val("");
        $("#book-content-table-hd").addClass('hide');
    }
    obj.remove();
}

/**
 * 选择图书回调
 * @param result
 */
function selectBookCallback(result) {
    if(result!=null && result.length>0){
        var bookIds = $('#bookIds').val();
        if(bookIds==null||bookIds==''){
            bookIds =',';
        }
        $.each(result,function (index,book) {
            var bookName =book.bookName;
            var bookPrice=book.bookPrice;
            if(bookIds.indexOf(","+book.id+",")==-1){
                $("#book-content-table-hd").removeClass("hide");
                bookIds +=book.id+',';
                $('#book-content').append(' <tr data-id="'+book.id+'">'+
                    '<td class="text-center">'+book.id+'</td>'+
                    '<td>'+bookName+'</td>'+
                    '<td><span class="c-red">'+bookPrice+'</span></td>'+
                    '<td class="text-center"><a class="c-master deleteBook"  href="javascript:void(0);">删除</a></td>'+
                    '</tr>');
            }
        });
        $('#bookIds').val(bookIds);
    }
}

/**
 * 删除会员
 * @param dataId 会员ID
 * @param obj
 */
function deleteMember(dataId, obj) {
    var memberIds = ',';
    var memberList = $("#memberIds").val();
    var memberIdArr = memberList.split(',');
    for (var i = 0; i < memberIdArr.length; i++) {
        if (memberIdArr[i] != null && memberIdArr[i] != '' && memberIdArr[i] != dataId) {
            memberIds += memberIdArr[i] + ",";
        }
    }
    if (memberIds.length > 1) {
        $("#memberIds").val(memberIds);
        $("#member-content-table-hd").removeClass('hide');
    } else {
        $("#memberIds").val("");
        $("#member-content-table-hd").addClass('hide');
    }
    obj.remove();
}

/**
 * 选择会员数据回调
 * @param result
 */
function selectMemberCallback(result) {
    if(result!=null && result.length>0){
        var memberIds = $('#memberIds').val();
        if(memberIds==null||memberIds==''){
            memberIds =',';
        }
        $.each(result,function (index,member) {
            var memberName =member.memberName;
            var memberPrice=member.memberPrice;
            if(memberIds.indexOf(","+member.id+",")==-1){
                $("#member-content-table-hd").removeClass("hide");
                memberIds +=member.id+',';
                $('#member-content').append(' <tr data-id="'+member.id+'">'+
                    '<td class="text-center">'+member.id+'</td>'+
                    '<td>'+memberName+'</td>'+
                    '<td><span class="c-red">'+memberPrice+'</span></td>'+
                    '<td class="text-center"><a class="c-master deleteMember"  href="javascript:void(0);">删除</a></td>'+
                    '</tr>');
            }
        });
        $('#memberIds').val(memberIds);
    }
}
/**
 * 选择回调
 */
function selectCall(em) {
    if (em.name == 'conditions') {
        openCourse(em.value);
    }
    if (em.name == 'settingStatus') {
        switchingConditions(em.value);
    }
    if (em.name == 'timeType') {
        timeType(em.value);
    }
    if (em.name == 'type') {
        couponType(em.value);
    }
    if(em.name=='orientType'){//针对类型
        orientType(em.value);
    }
    if(em.name=='userType'){//添加用户类型
        userType(em.value);
    }
}

/**
 * 控制免费直播
 * @param value
 */
function openCourse(value) {
    if (value == 6) {
        $(".openCourse").show();
    } else {
        $(".openCourse").hide();
        $("#courseOpen-content-table-hd").addClass("hide");
        $("#courseOpen-content").html("");
        $("input[name='openCourseIds']").val("");
    }
}

/**
 * 控制时间类型
 * @param value
 */
function timeType(value) {
    if (value == 1) {
        $(".timeType").show();
    } else {
        $(".timeType").hide();
    }
}

/**
 * 控制优惠券类型
 * @param value
 */
function couponType(value) {
    if (value == 1) {
        $('.discountCoupon').html('<i class="fa fa-tag"></i>');
        $('.fixedCoupon').html('折')
    } else if (value == 2) {
        $('.discountCoupon').html('<i class="fa fa-cny"></i>');
        $('.fixedCoupon').html('元')
    }
}

/**
 * 针对类型的切换
 * @param value
 */
function orientType(value) {
    if(value == 1){
        $("#orient-type-user").removeClass("hide");
        $("#orient-type-scene").addClass("hide");
    }else{
        $("#orient-type-scene").removeClass("hide");
        $("#orient-type-user").addClass("hide");
    }
}

/**
 * 添加用户类型
 * @param value
 */
function userType(value) {
    if(value==1){
        $("#part-user-type-box").addClass("hide");
    }else{
        $("#part-user-type-box").removeClass("hide");
    }
}

/**
 * 切换使用条件
 * @param str
 */
function switchingConditions(str) {
    if(str==1){//设置条件
        $(".shop-data-box").removeClass('hide');
    }else{//不设置条件Z
        $(".shop-data-box").addClass('hide');
    }
}

function isNumber(str) {//正整数验证
    var number = /^[0-9]+$/;
    if (number.test(str)) {
        return true;
    }
    return false;
}

function isDecimalAndInteger(str) {//验证正整数和小数
    var decimalAndInteger = /^[\d]+\.?[\d]{0,2}$/;
    if (decimalAndInteger.test(str)) {
        return true;
    }
    return false;
}

/**
 * 保存优惠券
 */
function saveCoupon() {
    $('body').on('click', "#submitSaveCoupon", function () {
        var couponCodeName = $('input[name="title"]').val();
        if (couponCodeName.trim() == '') {
            icModale(0, "请填写优惠券名称");
            return;
        }
        var couponCodeNum = $('input[name="codeNum"]').val();
        if (couponCodeNum == null || couponCodeNum <= 0) {
            icModale(0, "优惠券数量不能为空");
            return;
        }
        if (isNumber(couponCodeNum) == false) {
            icModale(0, "优惠券数量只能为正整数");
            return;
        }
        if (couponCodeNum > 10000) {
            icModale(0, "优惠券数量只能为正整数并且不能超过10000条");
            return;
        }
        var couponCouponBatch = $('input[name="couponBatch"]').val();
        if (!isLettersAndNumbers(couponCouponBatch)) {
            icModale(0, "优惠券批次只能有数字或字母或数字和字母组成");
            return;
        }
        var getLimitAtion = $('input[name="limitAtion"]').val();
        if (isDecimalAndInteger(getLimitAtion) == false) {
            icModale(0, "请正确输入优惠金额和折扣");
            return;
        }
        if ($("div.checked").find("input[name='type']").val()== 1) {
                if(getLimitAtion>=10){
                    icModale(0, "折扣券的折扣不能大于或等于10");
                    return;
                }
        }
        if ($("div.checked").find("input[name='type']").val()== 2) {
            if(isNumber(getLimitAtion)==false){
                icModale(0, "当为定额券的类型时，优惠券金额只能为正整数");
                return;
            }
        }
        var getMinAmount = $('input[name="minAmount"]').val();
        if (getMinAmount.length == 0) {
            icModale(0, "请输入限定消费限额");
            return;
        }
        if (isNumber(getMinAmount) == false) {
            icModale(0, "请正确输入限定消费限额，限定消费限额只能为正整数");
            return;
        }
        var params = $("#saveCouponFrom").serializeJSON();
        var shopData = {};
        shopData.courseIds = params.courseIds;
        delete params.courseIds;
        shopData.examIds = params.examIds;
        delete params.examIds;
        shopData.bookIds = params.bookIds;
        delete params.bookIds;
        shopData.memberIds = params.memberIds;
        delete params.memberIds;

        var qaUse = params.qaUse;
        if(typeof qaUse =='undefined'){
            qaUse = 'off';
            params.qaUse = qaUse;
        }
        shopData.qaUse = params.qaUse;
        delete params.qaUse;

        var attendUse = params.attendUse;
        if(typeof attendUse =='undefined'){
            attendUse = 'off';
            params.attendUse = attendUse;
        }
        shopData.attendUse = params.attendUse;
        delete params.attendUse;
        params.shopData = shopData;

        //设置类型
        var receiveType = $("#receive-type>li.active").data('type');
        var orientType = 0;
        var userType = 0;
        var conditions = 0;
        var shopList = new Array();
        if(receiveType==2){
            orientType = $("input[name='orientType']:checked").val();
            if(orientType==1){
                userType = $("input[name='userType']:checked").val();
                if(userType==2){
                    var shopListBox = $("#part-user-type-box").find('[data-type]');
                    if(shopListBox.length > 0){
                        $.each(shopListBox,function (index,shop) {
                            var shopObj = {};
                            shopObj.shopId = $(shop).data('id');
                            shopObj.shopType = $(shop).data('type');
                            shopList.push(shopObj);
                        });
                    }
                }
            }else if(orientType ==2){
                conditions = $("input[name='conditions']:checked").val();
            }
        }
        params.receiveType = receiveType;
        params.orientType = orientType;
        params.userType = userType;
        params.conditions = conditions;
        params.opCouponTermShopList = shopList;
        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + "/admin/op/coupon/saveOpCoupon",
            type: "post",
            data: params,
            dataType: "json",
            contentType:'application/json;charset=utf-8',
            beforeSend: function (XHR) {
                icModale(0, '数据保存中，请耐心等待...');
                $("#submitSaveCoupon").attr({disabled: "disabled"});
                return true;
            },
            success: function (result) {
                if (result.success == true) {
                    icModale(0, result.message)
                    $("#submitSaveCoupon").prop("disabled", false);
                    window.location.href = baseloaction + "/admin/op/coupon/toOpCouponListPage"
                } else {
                    $("#submitSaveCoupon").prop("disabled", false);
                    icModale(0, result.message);
                }
            },
            error: function (error) {
                $("#submitSaveCoupon").prop("disabled", false);
                icModale(0, '系统错误，数据加载失败');
            }
        });
    });
}

/**
 * 选择免费直播
 */
function selectOpenCourse() {
    $('body').on('click', '#selectOpenCourse', function () {
        //var subjectIds = $("input[name='subjectIds']").val();
        //选择免费直播程
        selectOpenCourseWind('checkbox','','callbackOpenCourse');
    });
}
/**
 * 选择免费直播程回调
 * @param openCourse
 */
function callbackOpenCourse(openCourse) {
    $("#courseOpen-content-table-hd").removeClass("hide");
    $.each(openCourse,function (index,course) {
        var openCourseIds = $("input[name='openCourseIds']").val();
        if(openCourseIds.indexOf(','+course.id+',')!=-1){
            return;
        }
        if(openCourseIds){
            $("input[name='openCourseIds']").val(openCourseIds+course.id+',');
        }else{
            $("input[name='openCourseIds']").val(','+course.id+',');
        }
        $('#courseOpen-content').append(' <tr data-id="' + course.id + '">' +
            '<td class="text-center">' + course.id + '</td>' +
            '<td>' + course.courseName + '</td>' +
            '<td>' + course.subjectName + '</td>' +
            '<td><span class="c-red">' + course.time + '</span></td>' +
            '<td class="text-center"><a class="c-master deleteOpenCourse"  href="javascript:void(0);">删除</a></td>' +
            '</tr>');
    });
}

/**
 * 删除免费直播程
 * @param dataId 免费直播程ID
 * @param obj 删除tr元素
 */
function deleteSelectOpenCourse(dataId, obj) {

    var openCourseIds = $('input[name="openCourseIds"]').val();
    if(openCourseIds){
        dataId = ','+dataId+',';
        openCourseIds = openCourseIds.replace(dataId,',');
        if(openCourseIds==','){
            $("#courseOpen-content-table-hd").addClass("hide");
            $("#courseOpen-content").html("");
            $("input[name='openCourseIds']").val("");
        }else{
            $("input[name='openCourseIds']").val(openCourseIds);
        }
    }else{
        $("#courseOpen-content-table-hd").addClass("hide");
        $("#courseOpen-content").html("");
        $("input[name='openCourseIds']").val("");
    }
    obj.remove();
}